#!/bin/sh
set -e
# install required dependencies
sed -i 's/mirrors.ustc.edu.cn/mirrors.tuna.tsinghua.edu.cn/g' /etc/apk/repositories
apk update
apk add py3-pip py3-yaml py3-regex py3-netifaces py3-psutil unzip py3-pillow ttyd ffmpeg git tzdata
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
#pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
echo "Asia/Shanghai" > /etc/timezone

mkdir -p /root/extensions/ttyd
cat << EOF > /root/extensions/ttyd/manifest.json
{
        "title": "Remote web terminal (ttyd)",
        "description": "Uses port 5002; User root / ssh password"
}
EOF

#echo "octoprint" > /root/.octoCredentials
cat << EOF > /root/extensions/ttyd/start.sh
#!/bin/sh
ttyd -p 5002 --credential root:\$(cat /root/.octoCredentials) bash
EOF

cat << EOF > /root/extensions/ttyd/kill.sh
#!/bin/sh
pkill ttyd
EOF

cat << EOF > /.start.sh
#!/bin/sh
nginx
/klipper-env/bin/python3 /klipper/klippy/klippy.py /root/klipper_config/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds&
LD_PRELOAD=/home/octoprint/ioctlHook.so /moonraker-env/bin/python3 /moonraker/moonraker/moonraker.py -c /root/klipper_config/moonraker.conf -l /tmp/moonraker.log&
ttyd -p 5002 --credential root:\$(cat /root/.octoCredentials) bash
EOF

cat << EOF > /.stop.sh
#!/bin/sh
pkill -f 'klippy\.py'
pkill -f 'moonraker\.py'
pkill -f 'screen\.py'
nginx -s stop
EOF

chmod +x /.start.sh
chmod +x /.stop.sh
chmod +x /root/extensions/ttyd/start.sh
chmod +x /root/extensions/ttyd/kill.sh
chmod 777 /.start.sh
chmod 777 /.stop.sh
chmod 777 /root/extensions/ttyd/start.sh
chmod 777 /root/extensions/ttyd/kill.sh
